package com.ambercrm.base;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.ClipboardManager;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.ambercrm.R;
import com.ambercrm.business.login.LoginActivity;
import com.ambercrm.common.Common;
import com.ambercrm.constant.Constant;
import com.ambercrm.dialog_utils.ProgressDialogUtils;
import com.ambercrm.eventbus_event.LogoutEvent;
import com.ambercrm.http.HttpUtils;
import com.ambercrm.tools.RandomTool;
import com.ambercrm.tools.SharedPreferencesHelper;
import com.ambercrm.tools.ToastUtils;

import java.util.HashMap;

import de.greenrobot.event.EventBus;

public class BaseActivity extends AppCompatActivity {
    public SharedPreferencesHelper sp = null;
    public Activity mContext;
    ProgressDialogUtils mProgressDialogUtils;
    protected boolean isMain = false;
    private Handler mBaseHandler;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setStatusBarWordsColorDark(true);
        sp = new SharedPreferencesHelper(this);
        if (Common.getInstance().getToken() == null) {
            String token = sp.getValue(Constant.sp_Token);
            if (token != null) {
                Common.getInstance().setToken(token);
            }
        }
        mContext = this;
        mProgressDialogUtils = new ProgressDialogUtils(this);
        EventBus.getDefault().register(this);
        mBaseHandler = new Handler();
    }

    // 弹出Toast
    public void toast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToast(msg);
            }
        });
    }

    // 打开一个Activity传递一个Bundle
    public void startActivity(Class<? extends Activity> target, Bundle bundle, boolean finish) {
        Intent intent = new Intent(this, target);
        if (bundle != null) {
            intent.putExtras(bundle);
        }

        startActivity(intent);
        overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
        if (finish) {
            finish();
        }
    }


    // 打开一个Activity传递一个boolean类型
    public void startActivity(Class<? extends Activity> target, String passDataKey, boolean value, boolean finish) {
        Intent intent = new Intent(this, target);
        if (passDataKey != null) {
            intent.putExtra(passDataKey, value);
        }
        startActivity(intent);
        overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
        if (finish) {
            finish();
        }
    }

    // 传R.color.xxx
    public void changeStatusColor(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.RED);   //这里动态修改颜色
            getWindow().setStatusBarColor(getResources().getColor(color));
        }
    }

    // 打开一个Activity
    public void startActivityForResult(Class<? extends Activity> target, int requestCode, Bundle bundle) {
        Intent intent = new Intent(this, target);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
    }

    // 获取上个界面传过来的Bundle
    public Bundle getBundle() {
        try {
            Intent it = getIntent();
            if (it != null && it.getExtras() != null) {
                return it.getExtras();
            }
        } catch (Exception e) {

        }

        return null;
    }

    public void finishActivity() {
        finish();
        overridePendingTransition(R.anim.comm_scale_in, R.anim.comm_slide_out_to_right);
    }

    public void finishActivityForResult(int resultCode, Bundle bundle) {
        Intent intent1 = new Intent();
        if (bundle != null)
            intent1.putExtras(bundle);
        setResult(resultCode, intent1);
        finish();
        overridePendingTransition(R.anim.comm_scale_in, R.anim.comm_slide_out_to_right);
    }

    public void finishActivityForResult(int resultCode) {
        finishActivityForResult(resultCode, null);
    }

    // 隐藏软键盘
    public void hideSoftKeyBoard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //隐藏键盘
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    // 显示软键盘
    public void showSoftKeyBoard(View view) {
        view.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //显示键盘
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    // 保存到剪切板
    public void saveToClipboard(String text) {
        ClipboardManager c = (ClipboardManager) getSystemService(Service.CLIPBOARD_SERVICE);
        c.setText(text);
        toast("已复制到剪切板");
    }

    //获取随机数， 参数为返回随机数的长度
    public String generateRandomString(int length) {
        return RandomTool.generateString(length);
    }

    public Display getScreenParams() {
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        return display;
    }

    // 设置屏幕亮度 0-255
    public void setScreenBrightness(int brightness) {
        Window window = this.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        if (brightness == -1) {
            lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        } else {
            lp.screenBrightness = (brightness < 0 ? 0 : brightness) / 255f;
        }
        window.setAttributes(lp);
    }

    // 获取屏幕亮度
    public int getSystemBrightness() {
        int systemBrightness = 0;
        try {
            systemBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
            if (systemBrightness < 100) {
                systemBrightness = 100;
            }
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return systemBrightness;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        try {
            sp = null;
            mContext = null;
            EventBus.getDefault().unregister(this);
            if (mProgressDialogUtils.isShowing()) {
                mProgressDialogUtils.dismiss();
                mProgressDialogUtils = null;
            }
        }
        catch (Exception e) {

        }
    }

    // 界面请求封装
    HttpUtils.OnResponseListener onResponseListener = new HttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(final String result, final int what) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    BaseActivity.this.onSucceed(result, what);
                }
            });
        }

        @Override
        public void onFailed(final String result, final int what) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    BaseActivity.this.onFailed(result, what);
                }
            });
        }

        @Override
        public void onFinish(final int what) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    BaseActivity.this.onFinish(what);
                }
            });
        }
    };

    protected void httpGet(String url, HashMap<String, String> params, int what, boolean isShowProgressDialog, String progressText) {
        if (isShowProgressDialog) {
            if (progressText != null) {
                mProgressDialogUtils.show(mContext, progressText, false, null);
            }
            else {
                mProgressDialogUtils.show(mContext);
            }
        }
        HttpUtils.httpGet(url, params, onResponseListener, what);
    }

    protected void httpPost(String url, int what, Object params, boolean isShowProgressDialog, String progressText) {
        if (isShowProgressDialog) {
            if (progressText != null) {
                mProgressDialogUtils.show(mContext, progressText, false, null);
            }
            else {
                mProgressDialogUtils.show(mContext);
            }
        }
        HttpUtils.httpPost(url, params, onResponseListener, what);
    }

    // 请求成功回调
    protected void onSucceed(String result, int what) {

    }

    // 请求失败回调
    protected void onFailed(String result, int what) {
        toast(result);
    }

    // 请求完成回调
    protected void onFinish(int what) {
        if (mProgressDialogUtils != null && mProgressDialogUtils.isShowing()) {
            mProgressDialogUtils.dismiss();
        }
    }

    public void showProgressDialog(Context context, String title) {
        if (mProgressDialogUtils != null) {
            if (!mProgressDialogUtils.isShowing()) {
                mProgressDialogUtils.show(context, title);
            }
        }
    }

    public void dismissProgressDialog() {
        if (mProgressDialogUtils != null) {
            if (mProgressDialogUtils.isShowing()) {
                mProgressDialogUtils.dismiss();
            }
        }
    }

    public void onEventMainThread(LogoutEvent event) {
        if (isMain) {
            // 如果是主界面，就删除token，然后跳转到登录界面， 800毫秒以后全部退出
            sp.deleteValue(this, Constant.sp_Token);
            startActivity(LoginActivity.class, null, false);
            Common.getInstance().setToken(null);
        }

        mBaseHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 800);
    }

    protected void setStatusBarWordsColorDark(boolean dark) {
        View decor = getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }

        try {
            MyApplication.getApplicationInstance().mIUISetStatusBarLightMode(this, dark);
        }
        catch (Exception e) {

        }

        try {
            MyApplication.getApplicationInstance().setFlymeLightStatusBar(this, dark);
        }
        catch (Exception e) {

        }
    }
}
